/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.hotel.protocol.server;

import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.hotel.model.ProtocolCmd;
import com.xdtech.hotel.protocol.cmd.CmdManager;
import com.xdtech.hotel.protocol.manager.DeviceMonitor;
import com.xdtech.hotel.protocol.manager.OperationManager;
import com.xdtech.hotel.protocol.vo.RCUDevice;
import com.xdtech.hotel.service.DeviceEventService;
import com.xdtech.hotel.service.ProtocolCmdService;
import com.xdtech.hotel.util.RedisUtils;

/**
 * 
 * @author max.zheng
 * @create 2015-5-25下午9:21:53
 * @since 1.0
 * @see
 */
public class SendHandler {
	private static Log log = LogFactory.getLog(SendHandler.class);
	
	public static void handlerCmdFirstResult() {
		new Thread(new Runnable()
		{
			public void run()
			{
				while (true)
				{
					try
					{
						Set<String> keysSet = RedisUtils.checkExistPostToDevice();
						String cmdAndResultContent = "";
				 		if (keysSet!=null&&keysSet.size()>0)
						{
							for (String key : keysSet)
							{
								cmdAndResultContent = RedisUtils.getPostCmdToDevcie(key);
								String sn = RedisUtils.getSNByKey(key);
								RCUDevice device = DeviceMonitor.monitorDevices.get(sn);
								ProtocolCmdService protocolCmdService = (ProtocolCmdService) ApplicationContextUtil.getContext().getBean("protocolCmdServiceImpl");
								String[] temps = cmdAndResultContent.split("#");
								String rs = "fail";
								if (temps[1].contains("true")) {
									rs = "success";
								}
								if (device!=null) {
									ProtocolCmd protocolCmd = new ProtocolCmd("SOFT_TO_DEV",sn,device.getIp(),device.getPort()+"",temps[0],temps[1],rs);
									protocolCmdService.save(protocolCmd);
									if("fail".equals(rs)) {
										//放入redis，等待二次发送    内容为：发送命令#命令id
										RedisUtils.addNeedSecondPostCmdToDevcie(sn, temps[0]+"#"+protocolCmd.getId());
									}
								}
								
							}
						}
				 		else
						{
							Thread.sleep(5000);
						}
					}
					catch (Exception e)
					{
						log.error("HandlerCmdFirstResult Error", e);
					}
				}
			}
		}, "HandlerCmdFirstResultThread").start();
	}
	
	public static void handlerCmdSecondResult() {
		new Thread(new Runnable()
		{
			public void run()
			{
				while (true)
				{
					try
					{
						Set<String> keysSet = RedisUtils.checkExistSecondPostToDevice();
						String cmdAndSecondCmdId = "";
				 		if (keysSet!=null&&keysSet.size()>0)
						{
							for (String key : keysSet)
							{
								cmdAndSecondCmdId = RedisUtils.getSecondPostCmdToDevcie(key);
								String sn = RedisUtils.getSNBySecondKey(key);
								RCUDevice device = DeviceMonitor.monitorDevices.get(sn);
								ProtocolCmdService protocolCmdService = (ProtocolCmdService) ApplicationContextUtil.getContext().getBean("protocolCmdServiceImpl");
								String[] temps = cmdAndSecondCmdId.split("#");
							    String rs = OperationManager.secondSendData(device.getSn(),device.getIp(), Integer.valueOf(device.getPort()), temps[0]);
								protocolCmdService.secondResultHandler(device, rs, Long.valueOf(temps[1]));
							}
						}
				 		else
						{
							Thread.sleep(5000);
						}
					}
					catch (Exception e)
					{
						log.error("HandlerCmdSecondResult Error", e);
					}
				}
			}
		}, "HandlerCmdSecondResultThread").start();
	}

	/**
	 * 启动发送结果处理线程和第二次发送线程
	 * @author max.zheng
	 * @create 2015-5-25下午11:09:04
	 * @modified by
	 */
	public static void startHandlerThread() {
		handlerCmdFirstResult();
		handlerCmdSecondResult();
	}
}
